package react.debounce;



import java.util.function.Consumer;

/**
 * @author shenenlu 2021年06月16日 上午00:01:28
 */
//@Slf4j
public class DebounceUtil {

    static  ThreadLocal<String> sss = new ThreadLocal<>();

    public static <T> Consumer<T> debounce(Consumer<T> consumer, long milliSeconds) {
        return new Consumer<T>() {
            Thread[] threads = {null};
            @Override
            public void accept(T t) {
                if(threads[0] != null) {
                    threads[0].interrupt();
                }
                threads[0] = new Thread(() -> {
                    try {
                        //首先sleep一段时间，然后执行函数
                        Thread.sleep(milliSeconds);
                        consumer.accept(t);
                        threads[0] = null;
                    } catch (InterruptedException e) {
                        //如果中途被interrupt就不执行函数
                    }
                });
                threads[0].start();
            }
        };
    }

}
